import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from app.core.config import settings

app = FastAPI(
    title="露营小程序API",
    description="为露营小程序和管理后台提供的后端API服务",
    version="0.1.0",
    # 定义OpenAPI的标签顺序和描述
    openapi_tags=[
        {"name": "微信小程序-认证", "description": "微信小程序用户认证相关接口"},
        {"name": "微信小程序-用户", "description": "微信小程序用户相关接口"},
        {"name": "微信小程序-笔记", "description": "微信小程序笔记/帖子相关接口"},
        {"name": "微信小程序-营地", "description": "微信小程序营地相关接口"},
        {"name": "微信小程序-消息", "description": "微信小程序消息/聊天相关接口"},
        {"name": "微信小程序-文件上传", "description": "微信小程序文件上传相关接口"},
        {"name": "微信小程序-推荐", "description": "微信小程序内容推荐相关接口"},
        {"name": "管理后台-用户管理", "description": "管理后台用户管理相关接口"},
        {"name": "管理后台-笔记管理", "description": "管理后台笔记/帖子管理相关接口"},
        {"name": "管理后台-营地管理", "description": "管理后台营地管理相关接口"},
        {"name": "管理后台-商家", "description": "管理后台商家管理相关接口"},
        {"name": "管理后台-统计", "description": "管理后台数据统计相关接口"},
    ]
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 实际生产中应该限制来源
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 导入路由
from app.api.endpoints import user, post, campsite, chat, auth, merchant, upload, stats, recommendation
from app.api.endpoints import admin_user, admin_post, admin_campsite

# 注册微信小程序接口路由
app.include_router(auth.router, tags=["微信小程序-认证"])
app.include_router(user.router, prefix="/users", tags=["微信小程序-用户"])
app.include_router(post.router, prefix="/posts", tags=["微信小程序-笔记"])
app.include_router(campsite.router, prefix="/campsites", tags=["微信小程序-营地"])
app.include_router(chat.router, prefix="/chat", tags=["微信小程序-消息"])
app.include_router(upload.router, prefix="/upload", tags=["微信小程序-文件上传"])
app.include_router(recommendation.router, prefix="/recommendation", tags=["微信小程序-推荐"])

# 注册管理后台接口路由
app.include_router(merchant.router, prefix="/merchants", tags=["管理后台-商家"])
app.include_router(stats.router, prefix="/stats", tags=["管理后台-统计"])

# 注册管理后台专用接口
app.include_router(admin_user.router, prefix="/admin/users", tags=["管理后台-用户管理"])
app.include_router(admin_post.router, prefix="/admin/posts", tags=["管理后台-笔记管理"])
app.include_router(admin_campsite.router, prefix="/admin/campsites", tags=["管理后台-营地管理"])

# 确保媒体目录存在
os.makedirs(settings.MEDIA_ROOT, exist_ok=True)

# 挂载静态文件目录
app.mount("/media", StaticFiles(directory=settings.MEDIA_ROOT), name="media")

@app.get("/")
async def root():
    """
    API根路径，返回API基本信息
    """
    return {
        "app": "露营小程序后端API",
        "version": "0.1.0",
        "status": "running"
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000) 